package com.atguigu.exam.service.impl;

import com.atguigu.exam.properties.MinioProperties;
import com.atguigu.exam.service.FileUploadService;
import io.minio.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

/**
 * projectName: com.atguigu.exam.service.impl
 *
 * @author: 赵伟风
 * description:
 */
@EnableConfigurationProperties(value = MinioProperties.class)
@Service
@Slf4j
public class FileUploadServiceImpl implements FileUploadService {
   @Autowired
   private MinioProperties minioProperties;
    @Override
    public String uploadFile(MultipartFile file) {
        try{
            MinioClient minioClient = MinioClient.builder()
                    .endpoint(minioProperties.getEndPoint())
                    .credentials(minioProperties.getAccessKey(), minioProperties.getSecretKey())
                    .build();
            //创建桶
            boolean found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioProperties.getBucketName()).build());
            if(!found){
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(minioProperties.getBucketName()).build());
                String policy = """
                            {
                              "Statement" : [ {
                                "Action" : "s3:GetObject",
                                "Effect" : "Allow",
                                "Principal" : "*",
                                "Resource" : "arn:aws:s3:::bucket1/*"
                              } ],
                              "Version" : "2012-10-17"
                            }""";
                minioClient.setBucketPolicy(SetBucketPolicyArgs.builder().bucket(minioProperties.getBucketName()).config( policy).build());
            }else{
                System.out.println("Bucket "+minioProperties.getBucketName()+" already exists");
            }
            //上传图片
            minioClient.uploadObject(UploadObjectArgs.builder()
                    .bucket("bucket1")
                    .object("lone")
                    .filename("E:\\lone.webp")
                    .build());
            System.out.println("上传成功");
        } catch (Exception e) {
            System.out.println("Error occurred: " + e);
        }

        return "";
    }
}
